package com.qianchang.microfinance.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.qianchang.microfinance.bean.Apps;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SSC on 2017/12/22.
 */

public class LocalAppManager {

    private Context mContext;
    private PackageManager pm;

    public LocalAppManager(Context context) {
        this.mContext = context;
        pm = context.getPackageManager();
    }

    /**
     * 得到手机中所有的应用程序信息
     *
     * @return
     */
    public List<Apps> getAppInfos() {
        //创建要返回的集合对象
        List<Apps> appInfos = new ArrayList<Apps>();
        //获取手机中所有安装的应用集合
        List<ApplicationInfo> applicationInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        //遍历所有的应用集合
        for (ApplicationInfo info : applicationInfos) {
            Apps appInfo = new Apps();
            //获取应用的名称
            String appname = info.loadLabel(pm).toString();
            appInfo.setName(appname);
            //获取应用的包名
            String packageName = info.packageName;
            try {
                //获取应用的版本号
                PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
                String app_version = packageInfo.versionName;
                appInfo.setVersion(app_version);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            //判断应用程序是否是用户程序
            boolean isUserApp = filterApp(info);
            if(isUserApp){
                appInfo.setIsUserApp(1);
            }else{
                appInfo.setIsUserApp(0);
            }
            appInfos.add(appInfo);
        }
        return appInfos;
    }

    //判断应用程序是否是用户程序
    public boolean filterApp(ApplicationInfo info) {
        //原来是系统应用，用户手动升级
        if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
            return true;
            //用户自己安装的应用程序
        } else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
            return true;
        }
        return false;
    }


}
